"use client";
import { notFound } from "next/navigation";
import NavBar from "@/app/components/NavBar";
import Footer from "@/app/components/Footer";
import Player from "@/app/components/Player";
import RatingComponent from "@/app/components/RatingComponent";
import VideoEditForm from "@/app/components/VideoEditForm";
import Modal from "@/app/components/Modal";
import { mockVideos } from "@/app/lib/mock";
import { use, useEffect, useState } from "react";
import { VideoItem } from "@/app/types/video";
import { runFullTest } from "@/app/lib/test-functions";

interface Params {
  params: Promise<{ id: string }>;
}

export default function WatchPage({ params: promiseParams }: Params) {
  const [video, setVideo] = useState<VideoItem | null>(null);
  const params = use(promiseParams);
  const [loading, setLoading] = useState(true);
  const [ratingLoading, setRatingLoading] = useState(false);
  const [favoriteLoading, setFavoriteLoading] = useState(false);
  const [message, setMessage] = useState<{text: string, type: 'success' | 'error'} | null>(null);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [isAdmin, setIsAdmin] = useState(false); // 模拟管理员状态，实际项目中应从认证系统获取
  const [isSaving, setIsSaving] = useState(false);
  const [isDownloading, setIsDownloading] = useState(false);
  
  // 模拟用户ID（实际项目中应该从认证系统获取）
  const userId = 1; // 这里使用固定值，实际应该从session或token中获取
  useEffect(() => {
    fetch(`/api/videos/${params.id}?userId=${userId}`)
      .then((res) => res.json())
      .then((data) => {
        if (data.success) {
          setVideo(data.data);
          // 模拟检查用户是否为管理员（实际项目中应从认证系统获取）
          // 这里简单地假设用户ID为1的是管理员
          setIsAdmin(userId === 1);
        } else {
          notFound();
        }
      })
      .catch(() => notFound())
      .finally(() => {
        setLoading(false);
      });
  }, [params.id, userId]);
  
  const handleRatingChange = async (rating: number) => {
    if (!video) return;
    
    setRatingLoading(true);
    try {
      const response = await fetch(`/api/videos/${video.id}?userId=${userId}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ rating })
      });
      
      const result = await response.json();
      if (result.success) {
        // 更新本地视频数据
        setVideo(prev => prev ? { ...prev, userRating: rating } : null);
        showMessage('评分成功', 'success');
      } else {
        showMessage(result.message || '评分失败', 'error');
      }
    } catch (error) {
      console.error('评分失败:', error);
      showMessage('评分失败，请稍后重试', 'error');
    } finally {
      setRatingLoading(false);
    }
  };
  
  const showMessage = (text: string, type: 'success' | 'error') => {
    setMessage({ text, type });
    setTimeout(() => {
      setMessage(null);
    }, 3000);
  };
  
  const handleToggleFavorite = async () => {
    if (!video) return;
    
    setFavoriteLoading(true);
    try {
      const response = await fetch(`/api/videos/${video.id}?userId=${userId}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ isFavorite: !video.isFavorite })
      });
      
      const result = await response.json();
      if (result.success) {
        // 更新本地视频数据
        setVideo(prev => prev ? { ...prev, isFavorite: !prev.isFavorite } : null);
        showMessage(!video.isFavorite ? '收藏成功' : '取消收藏成功', 'success');
      } else {
        showMessage(result.message || '操作失败', 'error');
      }
    } catch (error) {
      console.error('收藏操作失败:', error);
      showMessage('操作失败，请稍后重试', 'error');
    } finally {
      setFavoriteLoading(false);
    }
  };
  
  const handleSaveVideo = async (updatedVideo: Partial<VideoItem>) => {
    if (!video || !isAdmin) {
      showMessage('您没有权限编辑视频', 'error');
      setIsEditModalOpen(false);
      return;
    }
    
    setIsSaving(true);
    try {
      const response = await fetch(`/api/videos/${video.id}?userId=${userId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(updatedVideo)
      });
      
      const result = await response.json();
      if (result.success) {
        // 更新本地视频数据
        setVideo(prev => prev ? { ...prev, ...updatedVideo } : null);
        setIsEditModalOpen(false); // 保存成功后关闭弹窗
        showMessage('视频信息更新成功', 'success');
      } else {
        showMessage(result.message || '更新失败', 'error');
      }
    } catch (error) {
      console.error('更新视频失败:', error);
      showMessage('更新失败，请稍后重试', 'error');
    } finally {
      setIsSaving(false);
    }
  };

  const handleRemoteDownload = async () => {
    if (!video || !video.sourceUrl) {
      showMessage('视频地址无效，无法下载', 'error');
      return;
    }

    setIsDownloading(true);
    try {
      // 构造文件名，使用视频标题并确保以.mp4结尾
      let filename = video.title || `video_${video.id}`;
      if (!filename.endsWith('.mp4')) {
        filename += '.mp4';
      }
      // 移除文件名中可能的特殊字符
      filename = filename.replace(/[<>"/\\|?*]/g, '_');

      const response = await fetch('http://192.168.5.156:8000/api/download/task', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          m3u8_url: video.sourceUrl,
          filename: filename
        })
      });

      const result = await response.json();
      if (result.success || response.ok) {
        showMessage('下载任务已提交', 'success');
      } else {
        showMessage(result.message || '下载任务提交失败', 'error');
      }
    } catch (error) {
      console.error('远程下载失败:', error);
      showMessage('下载任务提交失败，请稍后重试', 'error');
    } finally {
      setIsDownloading(false);
    }
  };
  return (
    <div className="min-h-screen">
      <NavBar />
      <main className="mx-auto w-full max-w-5xl px-4 py-6">
        <div className="max-w-3xl mx-auto">
          {!loading && video && (
            <>
              <div>
                <Player url={video.sourceUrl ?? ""} />
                <h1 className="mt-4 text-xl font-semibold">{video.title}</h1>
                
                {/* 操作栏：评分、收藏、下载和编辑 */}
                <div className="mt-4 flex flex-col sm:flex-row sm:items-center gap-4">
                  {/* 评分组件 */}
                  <RatingComponent 
                    averageRating={video.averageRating || null}
                    ratingCount={video.ratingCount || 0}
                    userRating={video.userRating || null}
                    onRatingChange={handleRatingChange}
                    readOnly={ratingLoading}
                  />
                  
                  {/* 收藏按钮 */}
                  <button
                    onClick={handleToggleFavorite}
                    disabled={favoriteLoading}
                    className={`flex items-center gap-2 px-4 py-2 rounded-md transition-colors ${video.isFavorite 
                      ? 'bg-red-100 text-red-600 hover:bg-red-200 dark:bg-red-900/30 dark:text-red-400 dark:hover:bg-red-900/50'
                      : 'bg-zinc-100 text-zinc-700 hover:bg-zinc-200 dark:bg-zinc-800 dark:text-zinc-300 dark:hover:bg-zinc-700'
                    }`}
                  >
                    {favoriteLoading ? (
                      <svg xmlns="http://www.w3.org/2000/svg" className="animate-spin -ml-1 mr-2 h-4 w-4 text-zinc-600" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                    ) : (
                      <svg 
                        xmlns="http://www.w3.org/2000/svg" 
                        width="18" 
                        height="18" 
                        viewBox="0 0 24 24" 
                        fill={video.isFavorite ? "currentColor" : "none"} 
                        stroke="currentColor" 
                        strokeWidth="2" 
                        strokeLinecap="round" 
                        strokeLinejoin="round"
                      >
                        <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
                      </svg>
                    )}
                    {video.isFavorite ? '取消收藏' : '收藏视频'}
                  </button>
                  
                  {/* 远程下载按钮 */}
                  <button
                    onClick={handleRemoteDownload}
                    disabled={isDownloading || !video.sourceUrl}
                    className={`flex items-center gap-2 px-4 py-2 rounded-md transition-colors ${isDownloading 
                      ? 'bg-zinc-200 text-zinc-500 dark:bg-zinc-700 dark:text-zinc-400 cursor-not-allowed'
                      : !video.sourceUrl
                        ? 'bg-zinc-200 text-zinc-500 dark:bg-zinc-700 dark:text-zinc-400 cursor-not-allowed'
                        : 'bg-green-100 text-green-600 hover:bg-green-200 dark:bg-green-900/30 dark:text-green-400 dark:hover:bg-green-900/50'
                    }`}
                  >
                    {isDownloading ? (
                      <svg xmlns="http://www.w3.org/2000/svg" className="animate-spin -ml-1 mr-2 h-4 w-4 text-zinc-600" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                    ) : (
                      <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                        <polyline points="7 10 12 15 17 10"></polyline>
                        <line x1="12" y1="15" x2="12" y2="3"></line>
                      </svg>
                    )}
                    远程下载
                  </button>
                  
                  {/* 测试按钮 */}
                   <button
                     onClick={() => runFullTest(video?.id || '')}
                     className="flex items-center gap-2 px-4 py-2 rounded-md transition-colors bg-blue-100 text-blue-600 hover:bg-blue-200 dark:bg-blue-900/30 dark:text-blue-400 dark:hover:bg-blue-900/50"
                   >
                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                      <path d="m14.5 2-6 6 2 2 4-4 4 4 2-2-6-6z"></path>
                      <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
                    </svg>
                    运行测试
                  </button>
                  
                  {/* 编辑按钮 - 仅管理员可见 */}
                  {isAdmin && (
                    <button
                      onClick={() => setIsEditModalOpen(true)}
                      className="flex items-center gap-2 px-4 py-2 bg-purple-100 text-purple-600 rounded-md hover:bg-purple-200 dark:bg-purple-900/30 dark:text-purple-400 dark:hover:bg-purple-900/50"
                    >
                      <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
                        <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
                      </svg>
                      编辑视频
                    </button>
                  )}
                </div>
                
                {/* 视频描述 */}
                {video.description && (
                  <p className="mt-4 text-sm text-zinc-600 dark:text-zinc-400">
                    {video.description}
                  </p>
                )}
                
                {/* 消息提示 */}
                {message && (
                  <div className={`mt-4 px-4 py-2 rounded-md text-sm ${message.type === 'success' ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-100' : 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-100'}`}>
                    {message.text}
                  </div>
                )}
              </div>
            </>
          )}
        </div>
      </main>
      <Footer />
      
      {/* 编辑视频弹窗 */}
      <Modal
        isOpen={isEditModalOpen}
        onClose={() => setIsEditModalOpen(false)}
        title="编辑视频"
        size="large"
      >
        <VideoEditForm
          video={video}
          onSave={handleSaveVideo}
          onCancel={() => setIsEditModalOpen(false)}
          isSaving={isSaving}
        />
      </Modal>
    </div>
  );
}
